package com.jn.rxjava.views;

import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.jn.rxjava.R;
import com.jn.rxjava.adapter.NewsAdapter;
import com.jn.rxjava.model.NewsResponse;
import com.jn.rxjava.service.NewsRepository;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class NewsActivity extends AppCompatActivity {
    private ImageView newsImage;
    private TextView newsDate;
    private RecyclerView newsRecyclerView;
    private CompositeDisposable disposables = new CompositeDisposable();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news);

        newsImage = findViewById(R.id.newsImage);
        newsDate = findViewById(R.id.newsDate);
        newsRecyclerView = findViewById(R.id.newsList);

        NewsRepository repository = new NewsRepository();
        disposables.add(repository.getNewsInfo()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this::displayNewsInfo, this::handleError));
    }

    private void displayNewsInfo(NewsResponse response) {
        if (response != null && response.getResult() != null) {
            NewsResponse.Result result = response.getResult();
            newsDate.setText(result.getDate());

            Glide.with(this)
                    .load(result.getImage())
                    .into(newsImage);

            NewsAdapter adapter = new NewsAdapter(result.getNews());
            newsRecyclerView.setAdapter(adapter);
        }
    }

    private void handleError(Throwable throwable) {
        // Handle error
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        disposables.clear();
    }
}
